

package com.maoshi.shop.security.api.filter;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.maoshi.shop.security.api.model.MaoshiUser;
import com.maoshi.shop.security.api.service.MaoshiUserDetailsService;
import com.maoshi.shop.security.comment.enums.App;
import com.maoshi.shop.security.comment.exception.UsernameNotFoundException;
import com.maoshi.shop.security.comment.exception.WxErrorException;
import com.maoshi.shop.security.comment.filter.MaoshiAuthenticationProcessingFilter;
import com.maoshi.shop.security.comment.model.AppConnect;
import com.maoshi.shop.security.comment.token.AuthenticationToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

/**
 * 该实现已经被废弃，建议使用com.maoshi.shop.security.api.filter.AppLoginAuthenticationFilter 进行登录
 */
@Deprecated
@Component
public class MiniAppAuthenticationFilter extends MaoshiAuthenticationProcessingFilter {


    private final MaoshiUserDetailsService maoshiUserDetailsService;

    private final WxMaService wxMaService;

    @Autowired
    public MiniAppAuthenticationFilter(MaoshiUserDetailsService maoshiUserDetailsService, WxMaService wxMaService) {
        super("/miniAppLogin");
        this.maoshiUserDetailsService = maoshiUserDetailsService;
        this.wxMaService = wxMaService;
    }

    @Override
    protected UserDetails getUserDetails(AuthenticationToken authentication) {
        MaoshiUser loadedUser = null;

        String code = authentication.getPrincipal();

        WxMaJscode2SessionResult session = null;

        AppConnect appConnect = new AppConnect();
        appConnect.setAppId(App.MINI.value());
        try {
            session = wxMaService.getUserService().getSessionInfo(code);

            loadedUser = maoshiUserDetailsService.loadUserByAppIdAndBizUserId(App.MINI,session.getOpenid());
        } catch (me.chanjar.weixin.common.error.WxErrorException e) {
            throw new WxErrorException(e.getMessage());
        } catch (UsernameNotFoundException var6) {
            if (session == null) {
                throw new WxErrorException("无法获取用户登陆信息");
            }
            appConnect.setBizUserId(session.getOpenid());
            appConnect.setBizUnionid(session.getUnionid());
            maoshiUserDetailsService.insertUserIfNecessary(appConnect);
        }

        if (loadedUser == null) {
            loadedUser = maoshiUserDetailsService.loadUserByAppIdAndBizUserId(App.MINI, appConnect.getBizUserId());
        }

        loadedUser.setSessionKey(session.getSessionKey());
        return loadedUser;
    }


}
